/*
 * Copyright (C) 2008  Young,Fey <fey.young@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */ 
package com.youngfey.wordmaster.database.tables

import com.youngfey.database.annotation.*
import com.youngfey.wordmaster.database.*
import static com.youngfey.wordmaster.database.Database.*

@Unique(['STATEMENT'])
@HasMany(['SentenceIndex', 'Review'])
public class Sentence {
    @Size(512)
    String statement
    
    @DefaultValue('1')
    Integer familiarity
    
    @DefaultValue('2')
    Integer importantly

    // <editor-fold defaultstate="collapsed" desc=" Generated Code (by gRDB)">
    Integer id
    

    boolean equals(Object o) {
        id != null && o instanceof Sentence && id == o.getId()
    }

    static createTable() {
        execute("CREATE TABLE Sentence (Id INT NOT NULL GENERATED ALWAYS AS IDENTITY CONSTRAINT SENTENCE_PK PRIMARY KEY, Statement VARCHAR(512) NOT NULL, Familiarity INT DEFAULT 1 NOT NULL, Importantly INT DEFAULT 2 NOT NULL)")
        
        execute('CREATE UNIQUE INDEX UIX_STATEMENT__SENTENCE ON Sentence (STATEMENT)')
        
    }

    boolean isValid() {
        statement?.size() <= 512 && familiarity != null && importantly != null
    }


    boolean isConflicted() {
    
        def idUIX_STATEMENT = findIdByUIX_STATEMENT(sTATEMENT)
        if(idUIX_STATEMENT != null && idUIX_STATEMENT != id) return true
    
        false
    }

    
    Integer findIdByUIX_STATEMENT(sTATEMENT) {
        firstRow("SELECT ID FROM Sentence WHERE STATEMENT = $sTATEMENT")?.id
    }
    


    static Sentence create(statement, familiarity, importantly) {
        def instance = new Sentence(statement: statement, familiarity: familiarity, importantly: importantly)
        instance.insert()
        instance
    }

    def insert() {
        if(id == null && isValid()) {
            id = executeInsert("INSERT INTO Sentence (Statement, Familiarity, Importantly) VALUES (${statement}, ${familiarity}, ${importantly})")[0][0]
            if(id != null) {
                
                return
            }
        }

        throw new IllegalStateException()
    }

    //capitalize;
    static Sentence find(Integer id) {
        if(id == null) return null

        

        def row = firstRow("SELECT * FROM Sentence WHERE Id = $id")
        
        row ? new Sentence(id: row.Id, statement: row.statement, familiarity: row.familiarity, importantly: row.importantly) : null
        
    }

    static ArrayList<Sentence> findBySql(stmt) {
        def rows = []
        eachRow(stmt) {row ->
            rows << new Sentence(id: row.Id, statement: row.statement, familiarity: row.familiarity, importantly: row.importantly)
        }
        
        rows
    }

    static ArrayList<Sentence> findAll() {
        findBySql('SELECT * FROM Sentence')
    }

    
    static ArrayList<Sentence> findAll(String keyword) {
        findBySql("SELECT * FROM Sentence WHERE (Statement LIKE $keyword)")
    }
    

    private executeUpdate(stmt) {
        def updated = executeUpdate(stmt)
        if(updated != 1) throw new IllegalStateException()
        
    }

    def update() {
        if(id != null && isValid()) {
            executeUpdate("UPDATE Sentence SET Statement = ${statement}, Familiarity = ${familiarity}, Importantly = ${importantly} WHERE Id = $id")
        }
    }

    static delete(Integer id) {
        execute("DELETE FROM Sentence WHERE Id = $id")
        
    }

    def delete() {
        if(id != null) delete(id)
    }


    static ArrayList<Sentence> findByStatement(value) {
        findBySql("SELECT * FROM Sentence WHERE Statement = ${value}")
    }

    static ArrayList<Sentence> findByFamiliarity(value) {
        findBySql("SELECT * FROM Sentence WHERE Familiarity = ${value}")
    }

    static ArrayList<Sentence> findByImportantly(value) {
        findBySql("SELECT * FROM Sentence WHERE Importantly = ${value}")
    }



    static ArrayList<Sentence> findByStatementLike(String keyword) {
        findBySql("SELECT * FROM Sentence WHERE Statement LIKE $keyword")
    }

    static ArrayList<Sentence> findByFamiliarityLike(String keyword) {
        findBySql("SELECT * FROM Sentence WHERE Familiarity LIKE $keyword")
    }

    static ArrayList<Sentence> findByImportantlyLike(String keyword) {
        findBySql("SELECT * FROM Sentence WHERE Importantly LIKE $keyword")
    }



    def updateStatement(value) {
        this.statement = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE Sentence SET Statement = ${value} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateFamiliarity(value) {
        this.familiarity = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE Sentence SET Familiarity = ${value} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateImportantly(value) {
        this.importantly = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE Sentence SET Importantly = ${value} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }



    ArrayList<SentenceIndex> getSentenceIndexList() {
        SentenceIndex.findBySentence(this)
    }

    ArrayList<Review> getReviewList() {
        Review.findBySentence(this)
    }

    // </editor-fold>
}
